var category_type = null;
var progect_type = null;
var project_hivetype = null;
var project_state = null;
var voltage_type = null;
var bprojectapplicationall = null;//申请书
var bbudgetstandardall = null;//预算标准
var orgall = null;//所有人员
var userall = null;//所有单位
var userallmy = null;
var all_department = null;//供电局
var construction = null; //施工队
var all_user = null; //施工备选参与人
var abc = null;//已选施工参与人
var def = null;
var map = null;
var pBReckonid=null;
var company_admin = null;//单位管理员
var svg;
$(function () {
    $.when(
        getdatadictionary("category_type"),
        getdatadictionary("progect_type"),
        getdatadictionary("project_hivetype"),
        getdatadictionary("build_project_type"),
        getdatadictionary("voltage_type"),
        getbprojectapplicationall(),
        getbbudgetstandardall(),
        getorgall(),
        getuserall(),
        getabc(),
        get_construction()
    ).done(
        $("#jqGrid").jqGrid({
            url: baseURL + 'csg/cpbase/list?state=isdelno&ourid=isok',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
                { label: '所属批次ID', name: 'bGuid', index: 'b_guid', width: 80,hidden:true },
                { label: '项目名称', name: 'pBName', index: 'p_b_name', width: 80 },
                { label: '项目类别', name: 'pBType', index: 'p_b_type', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in progect_type) {
                            if (cellvalue == progect_type[d].dKey) return progect_type[d].dValue;
                        }
                    }
                },
                { label: '业务类型', name: 'pBCategory', index: 'p_b_category', width: 80,hidden:true,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in category_type) {
                            if (cellvalue == category_type[d].dKey) return category_type[d].dValue;
                        }
                    } },
                { label: '储备状态', name: 'pBHive', index: 'p_b_hive', width: 80,hidden:true },
                { label: '项目状态', name: 'pBState', index: 'p_b_state', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in project_state) {
                            if (cellvalue == project_state[d].dKey) return project_state[d].dValue;
                        }
                    }
                },
                { label: '项目地址', name: 'pBAddress', index: 'p_b_address', width: 80,hidden:true },
                { label: '项目经度', name: 'pBLongitude', index: 'p_b_longitude', width: 80,hidden:true },
                { label: '项目纬度', name: 'pBLatitude', index: 'p_b_latitude', width: 80,hidden:true },
                { label: '项目单位', name: 'pBOrgid', index: 'p_b_orgid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {

                        for (d in orgall) {
                            if (cellvalue == orgall[d].deptId)
                                return orgall[d].name;
                        }
                    }
                },
                { label: '所属申请书', name: 'aGuid', index: 'a_guid', width: 80,hidden:true },
                { label: '所属预算标准', name: 'sGuid', index: 's_guid', width: 80,hidden:true },
                { label: '最高电压等级', name: 'pBVoltage', index: 'p_b_voltage', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        var aa = " ";
                        if (cellvalue.length == 0){
                            return aa;
                        }

                        for (d in voltage_type) {
                            if (cellvalue == voltage_type[d].dKey) return voltage_type[d].dValue;
                        }
                    }
                },
                { label: '项目参与人', name: 'pBCollectid', index: 'p_b_collectid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";


                        var ss = (cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "") + "").split(",");
                        for (var i = 0; i < ss.length; i++) {

                            for (d in userall) {
                                if (ss[i] == userall[d].userId + "") {

                                    names += userall[d].username + ",";
                                }
                            }
                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },
                { label: '施工参与人', name: 'pBReckonid', index: 'p_b_reckonid', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";


                        var ss = (cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "") + "").split(",");
                        for (var i = 0; i < ss.length; i++) {

                            for (d in abc) {
                                if (ss[i] == abc[d].userId + "") {

                                    names += abc[d].username + ",";
                                }
                            }
                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },
                { label: '创建时间', name: 'pBAddtime', index: 'p_b_addtime', width: 80,hidden:true,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd hh:mm'):"";
                    }
                },
                { label: '项目申请书名称', name: 'pBBookname', index: 'p_b_bookname', width: 80,hidden:true },
                { label: '估算调整日期', name: 'pBChangetime', index: 'p_b_changetime', width: 80,hidden:true },
                { label: '数据状态', name: 'pBDatastate', index: 'p_b_datastate', width: 80,hidden:true },
                { label: '是否作图', name: 'isDraw', index: 'is_draw', width: 80,hidden:true },
                {label: '操作', name: '', width: 100, formatter: function (cellvalue, options, rowObject) {
                    // return   "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showgs(\"" + rowObject.guid + "\",\"" + rowObject.pBType + "\")' >&nbsp;进入验收阶段</a>"
                    return "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='archives(\"" + rowObject.guid + "\")' >&nbsp;归档</a>"
                    // + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportsssDXF(\"" + rowObject.guid + "\",\"" + rowObject.pBName + "\")' >&nbsp;导出DXF文件</a>"
                    //     + "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showDXF(\"" + rowObject.guid + "\",\"" + rowObject.pBName + "\")' >&nbsp;单线图</a>"
                }
                }
            ],
            viewrecords: true,
            height: 385,
            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        })
    )

    // svg = Snap("#singleLine");
    // svg_init();
    // var svg;
    // svg = Snap("#singleLine");//创建窗口

    /*map= new AMap.Map("container", {
     zoom: 18,
     resizeEnable: true,
     center: [106.949215,27.70325]
     });
     map.on('click', function(e) {
     alert('您在[ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ]的位置设置成了项目地址！');
     vm.getdiwei(e.lnglat.getLng(),e.lnglat.getLat());
     });
     AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

     var poiPicker = new PoiPicker({
     input: 'searchInput',
     placeSearchOptions: {
     map: map,
     pageSize: 10
     },
     searchResultsContainer: 'searchResults'
     });

     poiPicker.on('poiPicked', function(poiResult) {

     poiPicker.hideSearchResults();

     var source = poiResult.source,
     poi = poiResult.item;

     if (source !== 'search') {

     //suggest来源的，同样调用搜索
     poiPicker.searchByKeyword(poi.name);

     } else {

     }
     });

     poiPicker.onCityReady(function() {
     poiPicker.searchByKeyword('遵义');
     });
     });*/
});








/**
 * 进入验收项目
 *
 * @param guid
 * @param ptype
 */
function showgs(guid,ptype)
{
    var guid = getSelectedRow();
    if(guid == null){
        return ;
    }
    var url = "csg/cpbase/gotosg" ;

    $.ajax({
        type: "POST",
        url: baseURL + url,
        contentType: "application/json",
        data: JSON.stringify(guid),
        success: function(r){
            if(r.code === 0){
                alert('操作成功', function(index){
                    vm.reload();
                });
            }else{
                alert(r.msg);
            }
        }
    });
}

/**
 *  导出DXF文件
 *
 *  2018-10-19 10:49:09(旧版)
 */
function exportsssDXF(guid,pBName) {
    //
    var url = "csg/cpbase/exportDXF?pGuid="+guid+"&pBName="+pBName ;
    location.href = baseURL + url;

}


/**
 * 跳转到查看单线图页面
 *
 * @param guid -- 项目ID和项目名称
 * 2018-11-19 10:49:09(新版)
 */
function showDXF(guid,pBName) {

    // var url = "ashowdxfandexp.html?pGuid="+guid+"&pBName="+pBName ;
    // location.href = url;

    var title ="单线图";
    // var pGuid = vm.q.pGuid;
    var content = "ashowdxf.html?guid=" + guid+"&pBName="+pBName;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['100%', '100%'],
        content: content
    });
}



/**
 * 归档
 *
 * @param guid
 */
function archives(guid)
{
    $.get(baseURL + "csg/cpbase/info/"+guid, function(r){
        if(r.cPBase.pBState != 30){
            layer.confirm('您是否要归档该项目？', {
                btn: ['取消', '归档'],btn1:function () {
                    layer.closeAll();
                },btn2:function () {
                    var url =  "csg/cpbase/archives" ;
                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(guid),
                        success: function(r){
                            if(r.code === 0){
                                alert('操作成功', function(index){
                                    vm.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        }else{
            alert("此项目已归档");
        }
    });

}


/**
 *  配网技改修理项目申请书
 */
function getbprojectapplicationall()
{
    $.get(baseURL + "api/bprojectapplication/select", function (r) {
        bprojectapplicationall = r.returnlist;
    });
}

/**
 *  预算标准
 */
function  getbbudgetstandardall()
{
    $.get(baseURL + "api/bbudgetstandard/select" , function (r) {
        bbudgetstandardall = r.returnlist;
    });
}

/**
 *  部门
 */
function  getorgall()
{
    $.get(baseURL + "sys/dept/selectall" , function (r) {
        orgall = r.returnlist;
    });
}

/**
 *  员工
 */
function  getuserall()
{
    $.get(baseURL + "sys/user/select" , function (r) {
        userall = r.returnlist;
        userallmy = r.myuserlist;
    });
    vm.userall=userall;
    vm.userallmy=userallmy;
}

/**
 *  选择器添加施工人员
 */
function addIt(){
    var input = document.getElementById("staff");
    var output = document.getElementById("Preservation");
    for(i = 0; i < input.length; i ++ )   {
        if(input[i].selected == true)      {
            if( output.length == 0){
                var option = new Option();
                option.text = input[i].innerText;
                option.value= input[i].value;
                output.add(option);
            }

            var isExist = false;
            for(j = 0; j < output.length; j ++ ){
                if (output[j].text ==  input[i].innerText){
                    isExist = true;
                    break;
                }
            }

            if (isExist == false){
                var option = new Option();
                option.text = input[i].innerText;
                option.value= input[i].value;
                output.add(option);
            }
        }
    }
}


/**
 *  选择器删除施工人员
 */
function deleteIt(){
    var output = document.getElementById("Preservation");
    for(i = 0; i<output.length; i++){
        if (output[i].selected == true){
//                output.options.removeChild(output[i--]);
            $("#Preservation").find("option:selected").remove();
        }
    }

}


function removeIndex() {
    var output = document.getElementById("Preservation");
    for(i = 0; i<output.length; i++){
        if (output[i].selected == true){
//                output.options.removeChild(output[i--]);
            $("#Preservation").find("option:selected").remove();
        }
    }
}


/**
 * 所有项目已选施工参与人
 */
function getabc() {

    $.get(baseURL + "csg/cpbase/selectShiGong" , function (r) {
        abc = r.returnlist;
    });
    vm.abc=abc;
}

/**
 *  单个项目已选施工人员查看
 * @param guid
 */
function getdef(guid) {

    $.get(baseURL + "csg/cpbase/selectIndividual?pGuid="+guid , function (r) {
        def = r.returnlist;
    });
    // vm.def=def;
}

/**
 *  部门(供电局)
 */
/*function  getall_department()
 {
 $.get(baseURL + "csg/cpbase/selectDepartment?id=1" , function (r) {
 all_department = r.returnlist;
 });
 vm.all_department=all_department;

 var te = $("#pArentid").find("option:selected").text();
 }*/


/**
 *  选择施工队
 */
/*function getPArent() {
 //获取所选供电局的guid
 var pArentid = $("#pArentid").val();

 //根据供电局ID获取所属辖施工队
 var url = baseURL+'csg/cpbase/selectDepartment?pArentid='+pArentid;

 $.get(url, function (data) {
 var allpArent = data.returnlist;
 if (allpArent) {
 $("#pArentname").empty();
 var h = "<option value=''>---请选择---</option>";
 for (var i = 0; i < allpArent.length; i++) {
 h += "<option value='" + allpArent[i]['deptId'] + "'>" + allpArent[i]['name'] + "</option>"
 }
 $("#pArentname").html(h);
 }
 }, "json");
 }*/

/**
 *  参与人员
 */
function  getall_user()
{
    /*var deptId = $("#pArentname").val();
     $.get(baseURL + "sys/user/selectToDeptid?id="+deptId , function (r) {
     all_user = r.returnlist;
     vm.all_user = all_user;
     });*/


    var deptId = $("#pArentname").val();

    var url = baseURL+'csg/cpbase/selectToDeptid?id='+deptId;

    $.get(url, function (data) {
        var all_user = data.returnlist;
        if (all_user) {
            $("#staff").empty();
            // var h = "<option value=''>---请选择---</option>";
            var h;
            for (var i = 0; i < all_user.length; i++) {
                h += "<option value='" + all_user[i]['userId'] + "'>" + all_user[i]['username'] + "</option>"
            }
            $("#staff").html(h);
        }
    }, "json");



}


/**
 *  施工队
 */
function  get_construction()
{
    $.get(baseURL + "csg/cpbase/selectDepartment" , function (r) {
        construction = r.returnlist;
    });
    vm.construction=construction;
}


/**
 *  施工人员选择器
 */
function getInfoss(){
    // var array = new Array();  //定义数组     
    // $("#Preservation option").each(function(){  //遍历所有option         
    //     var txt = $(this).val();   //获取option值          
    //     if(txt!=''){
    //         array.push(txt);  //添加到数组中         
    //     }
    // })
    // pBCollectid.push(array);



    var obj = document.getElementById("Preservation");    //   $("#s2")选择的值
    var chooseStr = "";
    var val;
    for (var i = 0; i < obj.length; i++) {
        val = obj.options[i].value;
        chooseStr += val + ",";
    }

    chooseStr = chooseStr.substring(0, chooseStr.length - 1);

    vm.cPBase.pBReckonid.push(chooseStr);
//     通过后台将双向选择器选的值传回给前台Inspection页面的${options }以及选择的位置数量${num}
//     window.location.href = "/csg/cpbase/save?options=" + chooseStr+ "&num=" + obj.length;

}


/**
 *  数据字典
 * @param sss
 */
function getdatadictionary(sss)
{

    $.get(baseURL + "api/bdatadictionary/select?d_code="+sss, function(r){
        if(sss=="category_type")
        {
            category_type=r.returnlist;
        }
        if(sss=="progect_type")
        {
            progect_type=r.returnlist;
        }
        if(sss=="project_hivetype")
        {
            project_hivetype=r.returnlist;
        }
        if(sss=="build_project_type")
        {
            project_state=r.returnlist;
        }
        if(sss=="voltage_type")
        {
            voltage_type=r.returnlist;
        }
        vm.category_type=category_type;
        vm.progect_type=progect_type;
        vm.project_hivetype=project_hivetype;
        vm.project_state=project_state;
        vm.voltage_type=voltage_type;


    });
}





var vm = new Vue({
    el:'#rrapp',
    data:{

        q:{
            pBType:null,
            pBHive:null,
            pBName:null,
            pBState:null
        },
        bprojectapplicationall:bprojectapplicationall,
        bbudgetstandardall : bbudgetstandardall,
        orgall : orgall,
        abc:abc,
        // def:def,
        userall : userall,
        userallmy : userallmy,
        construction:construction,
        all_user:all_user,
        pBReckonid:pBReckonid,
        all_department : all_department,
        showList: true,
        title: null,
        cPBase: {pBCollectid:[],pBReckonid:[]},
        status: ["是", "否"],
        category_type:category_type,
        progect_type:progect_type,
        project_hivetype:project_hivetype,
        project_state:project_state,
        voltage_type:voltage_type
    },
    methods: {
        query: function () {
            vm.reload();
        },
        getdiwei:function (Longitude,Latitude)
        {
            vm. aPBase.pBLongitude=Longitude;
            vm. aPBase.pBLatitude=Latitude;
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.cPBase = {pBCollectid:[],pBReckonid:[]};
            // vm.aPBase={pBCollectid: [],pBLongitude:null,pBLatitude:null},
            vm.category_type=category_type;
            vm.progect_type=progect_type;
            vm.project_hivetype=project_hivetype;
            vm.project_state=project_state;
            vm.voltage_type=voltage_type;
            vm.userall= userall;
            vm.userallmy=userallmy;
            vm.construction=construction;
            vm.abc = abc;
            vm.all_user=all_user;
            vm.all_department=all_department;
            vm.pBReckonid = pBReckonid;
            // deleteIt();
        },
        update: function (event) {
            var guid = getSelectedRow();
            if(guid == null){
                return ;
            }

            $.get(baseURL + "csg/cpbase/info/"+guid, function(r) {
                if (r.cPBase.pBState == 30) {
                    alert("项目已归档，无法修改项目信息！");
                }else{

                    vm.showList = false;
                    vm.title = "修改";

                    vm.getInfo(guid)
                }
            });
        },
        saveOrUpdate: function (event) {

            //获取选择器所添加的施工人员
            var obj = document.getElementById("Preservation");    //   $("#s2")选择的值
            var chooseStr = "";

            var val;

            for (var i = 0; i < obj.length; i++) {
                val = obj.options[i].value;

                chooseStr += val + ",";

            }

            chooseStr = chooseStr.substring(0, chooseStr.length - 1);

            //去重
            vm.cPBase.pBReckonid.splice(0,vm.cPBase.pBReckonid.length);
            //添加施工人员
            vm.cPBase.pBReckonid.push(chooseStr);

            // console.log("vm.cPBase.pBReckonid=="+JSON.stringify(vm.cPBase.pBReckonid))

            var url = vm.cPBase.guid == null ? "csg/cpbase/save" : "csg/cpbase/update";


                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.cPBase),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                                // console.log("saveOrUpdate===>>>刷新成功！！！")
                                location.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });

        },
        del: function (event) {
            var guids = getSelectedRows();
            if(guids == null){
                return ;
            }
            var guid=guids[0];
            $.get(baseURL + "csg/cpbase/info/"+guid, function(r) {
                if (r.cPBase.pBState != 30) {
                    confirm('确定要删除选中的记录？', function () {
                        $.ajax({
                            type: "POST",
                            url: baseURL + "csg/cpbase/delete",
                            contentType: "application/json",
                            data: JSON.stringify(guids),
                            success: function (r) {
                                if (r.code == 0) {
                                    alert('操作成功', function (index) {
                                        $("#jqGrid").trigger("reloadGrid");
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    });
                }else{
                    alert("项目已归档，无法删除项目信息！")
                }
            })
        },
        getInfo: function(guid){
            $.get(baseURL + "csg/cpbase/info/"+guid, function(r){
                vm.cPBase = r.cPBase;
                vm.cPBase.pBReckonid = r.cPBase.pBReckonid.replace(/\"/g, "").replace("[", "").replace("]", "").split(",");
                vm.cPBase.pBCollectid = r.cPBase.pBCollectid.replace(/\"/g, "").replace("[", "").replace("]", "").split(",");
                // console.log("getInfo="+JSON.stringify(vm.cPBase))

            });
            get_construction();
            getabc();
            getdef(guid);
            getuserall();
            // getall_department();
        },
        reload: function (event) {

            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            var pBType =  vm.q.pBType;
            var pBHive =  vm.q.pBHive;
            var pBName =  vm.q.pBName;
            var pBState =  vm.q.pBState;
            $("#jqGrid").jqGrid('setGridParam',{
                /*postData:{
                    'pBType': vm.q.pBType,
                    'pBHive': vm.q.pBHive,
                    'pBName': vm.q.pBName,
                    'pBState': vm.q.pBState

                },*/
                url: baseURL + 'csg/cpbase/list?pBType='+pBType+'&pBHive='+pBHive+'&pBName='+pBName+'&pBState='+pBState,
                page:page
            }).trigger("reloadGrid");
            // console.log("reload===>>>刷新成功！！！")
            // location.reload();
        }
    }
});